﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace ES.Shared.Data
{
    [Serializable]
    public class KeyInfoCollection : Collection<KeyInfo>
    {
        public void AddRange(IEnumerable<KeyInfo> items)
        {
            foreach (KeyInfo item in items)
            {
                Add(item);
            }
        }

        public KeyInfo this[string IndexName]
        {
            get
            {
                KeyInfo found = FindKeyByKeyName(IndexName).FirstOrDefault();

                if (found == null)
                    throw new KeyNotFoundException();

                return found;
            }
        }

        private IEnumerable<KeyInfo> FindKeyByKeyName(string indexName)
        {
            return from index in this
                   where index.KeyName.Equals(indexName, StringComparison.InvariantCultureIgnoreCase)
                   select index;
        }

        private bool ExistsPrimaryKey()
        {
            return (from index in this
                    where index.KeyType == KeyType.PrimaryKey
                    select index).Count() > 0;
        }

        protected override void InsertItem(int index, KeyInfo item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            if (FindKeyByKeyName(item.KeyName).Count() == 0)
            {
                if (item.KeyType == KeyType.PrimaryKey)
                {
                    if (ExistsPrimaryKey())
                        throw new ArgumentException(LanguageResource.Error_PrimaryKeyExistsAlready);
                }
                base.InsertItem(index, item);
            }
            else
                throw new ArgumentException(string.Format(LanguageResource.Error_DoubleIndexName, item.KeyName));
        }

        protected override void SetItem(int index, KeyInfo item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            if (FindKeyByKeyName(item.KeyName).Count() == 0)
            {
                if (item.KeyType == KeyType.PrimaryKey)
                {
                    if (ExistsPrimaryKey())
                        throw new ArgumentException(LanguageResource.Error_PrimaryKeyExistsAlready);
                }
                base.SetItem(index, item);
            }
            else
                throw new ArgumentException(string.Format(LanguageResource.Error_DoubleIndexName, item.KeyName));
        }
    }
}
